from app import db
from datetime import datetime

class User(db.Model):
    """用户模型"""
    __tablename__ = 'users'
    
    id = db.Column(db.Integer, primary_key=True)
    openid = db.Column(db.String(100), unique=True, nullable=False, comment='微信openid')
    unionid = db.Column(db.String(100), comment='微信unionid')
    nickname = db.Column(db.String(50), comment='微信昵称')
    avatar_url = db.Column(db.Text, comment='头像URL')
    gender = db.Column(db.SmallInteger, default=0, comment='性别：0未知，1男，2女')
    phone = db.Column(db.String(20), comment='手机号')
    created_at = db.Column(db.DateTime, default=datetime.utcnow)
    updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
    last_login_at = db.Column(db.DateTime, default=datetime.utcnow, comment='上次登录时间')
    
    # 关联关系
    exam_records = db.relationship('ExamRecord', backref='user', lazy='dynamic')
    certificates = db.relationship('Certificate', backref='user', lazy='dynamic')
    leaderboards = db.relationship('Leaderboard', backref='user', lazy='dynamic')
    operation_logs = db.relationship('OperationLog', backref='user', lazy='dynamic')
    article_likes = db.relationship('UserArticleLike', backref='user', lazy='dynamic')
    article_collections = db.relationship('UserArticleCollection', backref='user', lazy='dynamic')
    
    def __repr__(self):
        return f'<User {self.nickname or self.openid}>'
    
    def to_dict(self):
        """转换为字典"""
        return {
            'id': self.id,
            'openid': self.openid,
            'nickname': self.nickname,
            'avatar_url': self.avatar_url,
            'gender': self.gender,
            'phone': self.phone,
            'created_at': self.created_at.isoformat() if self.created_at else None,
            'updated_at': self.updated_at.isoformat() if self.updated_at else None
        }
    
    @property
    def exam_count(self):
        """考试次数"""
        return self.exam_records.count()
    
    @property
    def pass_count(self):
        """通过次数"""
        return self.exam_records.filter_by(is_passed=True).count()
    
    @property
    def total_score(self):
        """总得分"""
        return sum(record.score for record in self.exam_records.all())
    
    @property
    def avg_score(self):
        """平均分"""
        records = self.exam_records.all()
        if not records:
            return 0
        return sum(record.score for record in records) / len(records)


class UserArticleLike(db.Model):
    """用户文章点赞关联表"""
    __tablename__ = 'user_article_likes'
    
    id = db.Column(db.Integer, primary_key=True)
    user_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=False)
    article_id = db.Column(db.Integer, db.ForeignKey('articles.id'), nullable=False)
    created_at = db.Column(db.DateTime, default=datetime.utcnow)
    
    # 创建联合唯一索引
    __table_args__ = (db.UniqueConstraint('user_id', 'article_id', name='unique_user_article_like'),)
    
    def __repr__(self):
        return f'<UserArticleLike {self.user_id}-{self.article_id}>'


class UserArticleCollection(db.Model):
    """用户文章收藏关联表"""
    __tablename__ = 'user_article_collections'
    
    id = db.Column(db.Integer, primary_key=True)
    user_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=False)
    article_id = db.Column(db.Integer, db.ForeignKey('articles.id'), nullable=False)
    created_at = db.Column(db.DateTime, default=datetime.utcnow)
    
    # 创建联合唯一索引
    __table_args__ = (db.UniqueConstraint('user_id', 'article_id', name='unique_user_article_collection'),)
    
    def __repr__(self):
        return f'<UserArticleCollection {self.user_id}-{self.article_id}>' 